package com.topica.network.download;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

import com.topica.R;
import com.topica.network.callback.OnDownloadListener;
import com.topica.util.Util;

public class DownloadFileTask extends AsyncTask<String, Integer, String> {

	public static final String LOG_TAG = "DownloadFile";

	private ProgressDialog mProgressDialog;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

	File rootDir = Environment.getExternalStorageDirectory();
	String directory = rootDir + "/topica/";
	String savePath;
	public String fileName;
	private Context context;
	private OnDownloadListener listener;

	public DownloadFileTask(Context context) {
		this.context = context;
	}

	public void setOnDownloadListener(OnDownloadListener l) {
		this.listener = l;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (!Util.isConnectingToInternet(context)) {
			Toast.makeText(context, R.string.network_error, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		checkAndCreateDirectory(directory);
		mProgressDialog = new ProgressDialog(context);
		mProgressDialog.setCancelable(false);
		mProgressDialog.setMessage(context.getResources().getString(
				R.string.loading));
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setMax(100);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.show();
	}

	@Override
	protected String doInBackground(String... params) {
		fileName = Util.getFileName(params[0]);
		int count = 0;
		ReadableByteChannel rbc = null;
		WritableByteChannel wbc = null;
		FileOutputStream out = null;
		ByteBuffer buffer;
		long mDownloadedBytes = 0;
		File file = new File(directory);
		if (!file.exists()) {
			file.mkdirs();
		}
		savePath = file + File.separator + fileName;
		try {
			URL url = new URL(params[0]);
			URLConnection conn = url.openConnection();
			conn.connect();
			int lenghtOfFile = conn.getContentLength();
			System.out.println("size " + lenghtOfFile);
			long threshold = (lenghtOfFile * 2) + 10;
			if (Util.getAvailableStorage() == Util.SDCARD_CANNOT_WRITE) {
				Toast.makeText(context, R.string.sdcard_error,
						Toast.LENGTH_SHORT).show();
				return "error";
			}
			if (Util.getAvailableStorage() == Util.NO_SDCARD) {
				Toast.makeText(context, R.string.no_sdcard, Toast.LENGTH_SHORT)
						.show();
				return "error";
			}
			if (!Util.checkAvailableStorage(threshold)) {
				return "not_enough_space";
			}
			rbc = Channels.newChannel(conn.getInputStream());
			out = new FileOutputStream(savePath);
			wbc = Channels.newChannel(out);
			while (count != -1) {
				buffer = ByteBuffer.allocate(256);
				count = rbc.read(buffer);
				if (count == 0) {
					continue;
				}
				if (count == -1)
					break;
				mDownloadedBytes += count;
				publishProgress((int) (mDownloadedBytes * 100 / lenghtOfFile));
				buffer.flip();
				while (buffer.hasRemaining())
					wbc.write(buffer);
			}
			wbc.close();
			rbc.close();
			out.close();
			wbc = null;
			out = null;
			rbc = null;
			// unzip
			// final Decompress dc = new Decompress(directory + fileName,
			// directory);
			// dc.unzip();

		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "success";
	}

	protected void onProgressUpdate(Integer... progress) {
		mProgressDialog.setProgress(progress[0]);
	}

	@Override
	protected void onPostExecute(String unused) {
		if (unused.equals("success")) {
			mProgressDialog.dismiss();
			listener.onDownloadComplete(fileName);
		} else if (unused.equals("not_enough_space")) {
			mProgressDialog.dismiss();
			Toast.makeText(context, R.string.sdcard_full, Toast.LENGTH_SHORT)
					.show();
		} else {
			mProgressDialog.dismiss();
			listener.onDownloadError();
		}
	}

	public void checkAndCreateDirectory(String dirName) {
		File new_dir = new File(dirName);
		if (!new_dir.exists()) {
			new_dir.mkdirs();
		}
	}

	// our progress bar settings
	// @Override
	// protected Dialog onCreateDialog(int id) {
	// switch (id) {
	// case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
	// mProgressDialog = new ProgressDialog(this);
	// mProgressDialog.setMessage("Downloading file...");
	// mProgressDialog.setIndeterminate(false);
	// mProgressDialog.setMax(100);
	// mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	// mProgressDialog.setCancelable(true);
	// mProgressDialog.setOnDismissListener(new OnDismissListener() {
	// @Override
	// public void onDismiss(DialogInterface dialog) {
	// removeDialog(DIALOG_DOWNLOAD_PROGRESS);
	// }
	// });
	// mProgressDialog.show();
	// return mProgressDialog;
	// default:
	// return null;
	// }
	// }
}